/**
 * @desc:快递配置列表页面
 * author：elvis
 */
import { useEffect, useState } from 'react';
import CommonTable from '@/components/CommonTable';
import CommonTag from "@/components/CommonTag";
import AddExpressModal from './common/AddExpressModal';
import AddNetwork from './common/AddNetwork';
import SetNetworkName from './common/SetNetworkName';
import AddFaceOrder from './common/AddFaceOrder';
import SetSelectArea from './common/SetSelectArea';
import SetWarehouse from './common/SetWarehouse';
import SetFreight from './common/SetFreight';
import AddSortCross from './common/AddSortCross';
import OperaBtnRender from '@/components/OperaBtnRender';
import { Popconfirm, Select, Switch, Tag, message, Popover, Tooltip } from 'antd';
import { PlusOutlined, EditOutlined } from '@ant-design/icons';
import { faceOrderTypeName } from '@/utils/config';
import { cloneDeep } from 'lodash';
import Iconfont from '@/components/IconFont';
import styles from '../index.module.less';
import {
  queryExpressList,
  queryAddressListOp,
  updateRelativeAddress,
  updateMatchStatus,
  removeExpress,
  removeWareHouse,
  removeNetwork,
  removeNetworkFace,
  getExpressDiscern,
  threeAreaStatus
} from '../service';

const { Option } = Select;

export default ({ query, tableKey }) => {
  const [expressList, setExpressList] = useState([]);

  const [addressList, setAddressList] = useState([]);
   
  const [visible, setVisible] = useState(1);

  const [item, setItem] = useState({});

  // 单条仓库唯一id用来判断气泡弹窗的开关
  const [storeHourseId, setStoreHourseId] = useState('');

  // 快递类型对应的map({id: type})
  const [expressDiscernMap, setExpressDiscernMap] = useState({});

  // 是否是京东快递
  const [jingDongVisible, setJingDongVisible] = useState(false);

  // 是否是顺丰快递
  const [shunFengVisible, setShunFengVisible] = useState(false);

  // 主列表的单条数据
  const [recordObj, setRecordObj] = useState({});

  useEffect(() => {
    queryAddressList();
  }, []);

  useEffect(() => {
    getExpressList();
  }, [tableKey]);

  //获取列表数据
  const getExpressList = async () => {
    START_LOADING();
    setExpressList([]);
    const { success, data } = await queryExpressList({
      ...query,
    });
    END_LOADING()
    if (success) {
      setExpressList(data);
    }
  };

  //获取寄件地址数据
  const queryAddressList = async () => {
    START_LOADING();
    const { success, data } = await queryAddressListOp({size: 50, current: 1});
    END_LOADING()
    if (success) {
      setAddressList(data?.records || []);
    }
  };

  //新增快递公司
  const handleAddExpress = () => {
    setVisible(2);
  };

  //删除快递公司
  const handleDeleteExpress = async (val) => {
    START_LOADING();
    const res = await removeExpress({
      expressTemplateId: val,
    });
    END_LOADING()
    if (res.success) {
      message.success('删除成功！');
      getExpressList();
    }
  };

  //新增网点
  const handleAddNetwork = (record) => {
    setItem(record);
    setVisible(3);
  };

  //修改网点名称
  const handleUpdateNetWorkName = (val) => {
    setItem(val);
    setVisible(4);
  };

  //设置分拣道口
  const handleSetUpCross = (record) => {
    setItem(record);
    setVisible("cross");
  }

  //点击添加面单获取平台
  const handleAddNetFace = (obj, record) => {
    if (expressDiscernMap[obj.expressId] == 2) {
      setShunFengVisible(true);
    } else {
      setShunFengVisible(false);
    }
    setItem({
      ...record,
      expressName: obj.expressName
    });
    setVisible(5);
  };

  //查看分配地区
  const handleLookArea = (record, obj) => {
    setItem({
      ...record,
      type: 'look',
      matchConfig: {
        title: '查看地区',
        expressName: obj.expressName,
      },
    });
    setVisible(6);
  };

  //设置网点是否启用
  const handleStatusChange = async (id) => {
    START_LOADING();
    const { success } = await updateMatchStatus({
      id,
    });
    END_LOADING()
    if (success) {
      message.success('设置成功！');
      getExpressList();
    }
  };

  //三方区域启用/禁用
  const handleAreaStatusChange = async (networkId, checked) => {
    START_LOADING();
    const { success } = await threeAreaStatus({
      networkId,
    });
    END_LOADING()
    if (success) {
        if(checked == 1) {
            message.success('关闭成功！');
        } else {
            message.success('开启成功！');
        }
      getExpressList();
    }
  }

  //删除可用仓库
  const handleDeleteWareHouse = async (val) => {
    START_LOADING();
    const res = await removeWareHouse({
      warehouseExpressId: val,
    });
    END_LOADING()
    if (res.success) {
      message.success('删除成功！');
      getExpressList();
    }
  };

  //新增可用仓库
  const handleAddWareHouse = (val, obj) => {
    if (expressDiscernMap[obj.expressId] == 1) {
      setJingDongVisible(true);
    } else {
      setJingDongVisible(false);
    }
    setItem(val);
    setVisible(7);
  };

  //修改运费
  const handleSetFreight = (val, obj) => {
    setItem(val);
    setVisible(8);
    setRecordObj(obj);
  };

  //编辑地区
  const handleSetArea = (record, obj) => {
    setItem({
      ...record,
      type: 'update',
      matchConfig: {
        title: '编辑地区',
        expressName: obj.expressName,
        expressId: obj.expressId,
      },
    });
    setVisible(6);
  };

  //删除网点
  const handleDeleteNet = async (networkId) => {
    START_LOADING();
    const res = await removeNetwork({
      networkId,
    });
    END_LOADING()
    if (res.success) {
      message.success('删除成功！');
      getExpressList();
    }
  };

  const columns = [
    {
      title: '快递公司',
      dataIndex: 'expressName',
      key: 'expressName',
      width: '80%',
      render: (text) => (
        <div>
          <span style={{ fontWeight: '600', fontSize: '16px' }}>{text}</span>
        </div>
      ),
    },
    {
      title: '操作',
      key: 'id',
      dataIndex: 'id',
      width: '20%',
      render: (text, record) => (
        <span className="opera-span-common">
          <span onClick={() => handleAddNetwork(record)}>新增网点</span>
          <i>|</i>
          <Popconfirm
            title="确定要删除该快递吗?"
            onConfirm={() => handleDeleteExpress(text)}
            okText="确定"
            cancelText="取消"
          >
            <span>删除</span>
          </Popconfirm>
        </span>
      ),
    },
  ];

  //官网对接排序在最前  后面的自然顺序（文档淘宝 京东 拼多多 抖音）
  const dealDataSort = (arr = [], obj) => {
    let newArr = [];

    if(obj.expressName.includes('顺丰速运')){
      newArr = arr.filter(item => item.platform == 5)
      arr.map(item=>{
        if(item.platform != 5){
          newArr.push(item)
        }
      })
    }else if(obj.expressName.includes('极兔速递')){
      newArr = arr.filter(item => item.platform == 2 || item.platform == 28)
      arr.map(item=>{
        if(item.platform != 2 && item.platform != 28){
          newArr.push(item)
        }
      })
    }else{
      newArr = arr
    }

    return newArr
  }

  const updateAddress = async (addressId, networkId) => {
    START_LOADING();
    const params = { networkId };
    if(addressId){
      params.addressId = addressId;
    }
    const { success } = await updateRelativeAddress(params);
    if(success){
      getExpressList();
      message.success(`寄件地址配置${addressId ? '已更新' : '已删除'}`);
    }else{
      END_LOADING()
    }
  }

  const expandedRowRender = (obj) => {
    const columns1 = [
      {
        title: '快递网点',
        dataIndex: 'networkName',
        key: 'networkName',
        width: 240,
        render: (text, record) => {
          if (text) {
            return (
              <div>
                <span>网点名称：{text}</span>
                <EditOutlined onClick={() => handleUpdateNetWorkName(record)} />
                {Boolean(record?.isUpDoor) && <div><CommonTag type='jdHomeDs' qmType/></div>}
              </div>
            );
          } else {
            return (
              <div>
                <span>网点名称：-</span>
                <EditOutlined className="common-color2" onClick={() => handleUpdateNetWorkName(record)} />
                {Boolean(record?.isUpDoor) && <div><CommonTag type='jdHomeDs' qmType/></div>}
              </div>
            );
          }
        },
      },
      {
        title: '面单获取平台',
        dataIndex: 'nfbs',
        key: 'nfbs',
        width: 200,
        render: (text, record) => {
         
          const arr = dealDataSort(text, obj)
          return (
            <>
              {arr.map((v) => (
                <div  key={v.id}>
                <Tag
                  closable
                  visible={true}
                  onClose={() => handleDeleteFace(v.id)}
                  style={{ margin: '4px' }}
                >
                  {faceOrderTypeName[v.platform]}-{v.ecstoreName}-
                  {v.networkName}
                  {Boolean(v?.isUpDoor) && <span className='common-color10'>（送货上门）</span>}
                </Tag>
                </div>
              ))}
              <Tag onClick={() => handleAddNetFace(obj, record)}>
                <PlusOutlined />
                添加
              </Tag>
            </>
          );
        },
      },
      {
        title: '分配地区',
        dataIndex: 'areas',
        key: 'areas',
        width: 95,
        render: (text, record) => {
          return (
            <span
              className="common-color2"
              onClick={() => handleLookArea(record, obj)}
            >
              查看地区
            </span>
          );
        },
      },
      {
        title: '寄件信息',
        dataIndex: 'addressId',
        key: 'addressId',
        width: 200,
        render: (text, record) => {
          return (
            <Select placeholder='请选择寄件信息' allowClear value={text} style={{width:220}} onChange={(e)=>updateAddress(e, record.networkId)}>
              {
                addressList.map(item=>{
                  return <Option key={item.id} value={item.id}><Tooltip title={item.fullAddress}>{item.fullAddress}</Tooltip ></Option>
                })
              }
            </Select>
          );
        },
      },
      {
        title: (
          <Popover
            content={
              <div style={{width: '300px'}}>
                  <p>1、开启，则表示该快递的可发地区从平台比如淘宝返回的数据读取</p>
                  <p>2、关闭，则表示可发地区从这里读取</p>
                  <p>注意：该开关目前只针对<span style={{color: '#D90A1A'}}>淘宝、京东、抖音、商城；</span>其他平台比如拼多多，极兔快递、官网快递等不受开关影响，还是从ERP读取可发地区</p>
              </div>
            }
          >
            <div>
             是否启用三方平台可发地区
              <Iconfont type="iconwenhao1" />
            </div>
          </Popover>),
        dataIndex: 'platformAreaStatus',
        key: 'platformAreaStatus',
        width: 180,
        render: (text, record) => (
          <Switch
            checkedChildren="已开启"
            unCheckedChildren="已关闭"
            checked={text == 1 ? true : false}
            onChange={() => handleAreaStatusChange(record.networkId, text)}
          />
        ),
      },
      {
        title: '分拣道口',
        dataIndex: 'outNum',
        key: 'outNum',
        width: 95,
        render: (text, record) => {
            return (
              <div>
                {text}
                <EditOutlined className="common-color2" onClick={() => handleSetUpCross(record)} />
              </div>
            );
        },
      },
      {
        title: '是否启用',
        dataIndex: 'status',
        key: 'status',
        width: 100,
        render: (text, record) => (
          <Switch
            checkedChildren="启用"
            unCheckedChildren="关闭"
            checked={text == 1 ? true : false}
            onChange={() => handleStatusChange(record.id)}
          />
        ),
      },
      {
        title: '可用仓库',
        dataIndex: 'wes',
        key: 'wes',
        width: 200,
        render: (text, record) => {
          return (
            <>
              {text.map((v) => (
                <Popconfirm
                  title="确定要删除该可用仓库吗？"
                  key={v.id}
                  visible={v.id == storeHourseId}
                  okText="确定"
                  cancelText="取消"
                  onConfirm={() => handleDeleteWareHouse(v.id)}
                  onCancel={() => setStoreHourseId('')}
                >
                  <Tag
                    closable
                    key={v.id}
                    visible={true}
                    // onClose={() => handleDeleteWareHouse(v.id)}
                    onClose={() => setStoreHourseId(v.id)}
                    style={{ margin: '4px' }}
                  >
                    {v.warehouseName}
                  </Tag>
                </Popconfirm>
              ))}
              <Tag onClick={() => handleAddWareHouse(record, obj)}>
                <PlusOutlined />
                添加
              </Tag>
            </>
          );
        },
      },
      {
        title: '操作',
        dataIndex: 'networkId',
        key: 'networkId',
        width: 160,
        render: (text, record) => (
          <span className="opera-span-common">
            <span onClick={() => handleSetFreight(record, obj)}>运费设置</span>
            <i>|</i>
            <span onClick={() => handleSetArea(record, obj)}>编辑地区</span>
            <i>|</i>
            <Popconfirm
              title="确定要删除该网点吗?"
              onConfirm={() => handleDeleteNet(text)}
              okText="确定"
              cancelText="取消"
            >
              <span>删除</span>
            </Popconfirm>
          </span>
        ),
      },
    ];

    const TableProps = {
      columns: columns1,
      rowKey: 'id',
      data: obj.networks || [],
    };
    return <CommonTable {...TableProps} />;
  };

  // 点击展开判断快递类型( 0：普通，1：京东，2：顺丰)
  const onExpandedRowsChange = (expandedRows) => {
    const expressDiscernMapObj = cloneDeep(expressDiscernMap);
    (expandedRows || []).map(async (id) => {
      if (!expressDiscernMap.hasOwnProperty(id)) {
        START_LOADING();
        const { success, data } = await getExpressDiscern({
          expressId: id,
        });
        if (success) {
          expressDiscernMapObj[id] = data;
          setExpressDiscernMap(expressDiscernMapObj);
        }
        END_LOADING()
      }
    });
  };

  const CommonTableProps = {
    data: expressList,
    columns,
    rowKey: 'expressId',
    expandable: {
      expandedRowRender,
      expandRowByClick: false,
      onExpandedRowsChange,
    },
  };

  //新增快递公司
  const AddExpressModalProps = {
    visible: visible == 2 ? true : false,
    handleOk() {
      setVisible(1);
      getExpressList();
    },
    handleCancel() {
      setVisible(1);
    },
  };

  //新增网点
  const AddNetworkProps = {
    visible: visible == 3 ? true : false,
    item,
    handleOk() {
      setVisible(1);
      getExpressList();
    },
    handleCancel() {
      setVisible(1);
    },
  };

  //删除面单获取平台
  const handleDeleteFace = async (id) => {
    START_LOADING();
    const res = await removeNetworkFace({
      ids: id,
    });
    END_LOADING()
    if (res.success) {
      message.success('删除成功！');
      getExpressList();
    }
  };

  //修改网点名称
  const SetNetworkNameProps = {
    visible: visible == 4 ? true : false,
    item,
    handleOk() {
      setVisible(1);
      setItem({});
      getExpressList();
    },
    handleCancel() {
      setVisible(1);
      setItem({});
    },
  };

  //添加面单获取平台
  const AddFaceOrderProps = {
    visible: visible == 5 ? true : false,
    item,
    shunFengVisible,
    handleOk() {
      setVisible(1);
      setItem({});
      getExpressList();
    },
    handleCancel() {
      setVisible(1);
      setItem({});
    },
  };

  //查看编辑地区
  const SetSelectAreaProps = {
    visible: visible == 6 ? true : false,
    item,
    handleOk() {
      setVisible(1);
      setItem({});
      getExpressList();
    },
    handleCancel() {
      setVisible(1);
      setItem({});
    },
  };

  //设置可用仓库
  const SetWarehouseProps = {
    visible: visible == 7 ? true : false,
    jingDongVisible,
    item,
    handleOk() {
      setVisible(1);
      setItem({});
      getExpressList();
    },
    handleCancel() {
      setVisible(1);
      setItem({});
    },
  };

  //设置运费
  const SetFreightProps = {
    visible: visible == 8 ? true : false,
    obj: item,
    recordObj,
    handleOk() {
      setVisible(1);
      setItem({});
      getExpressList();
    },
    handleCancel() {
      setVisible(1);
      setItem({});
    },
  };

  //设置分拣道口
  const AddSortCrossProps = {
    visible: visible == 'cross' ? true : false,
    record: item,
    handleOk() {
      setVisible(1);
      setItem({});
      getExpressList();
    },
    handleCancel() {
      setVisible(1);
      setItem({});
    },
  }

  //操作按钮
  const btnArr = [
    { elType: 'button', text: '新增快递公司', onClick: handleAddExpress }
  ]

  return (
    <>
      <OperaBtnRender  btnArr={btnArr} />
      <div className={styles.tableTitle}>异常订单称重机道口：-1</div>
      <CommonTable {...CommonTableProps} />
      {visible == 2 && <AddExpressModal {...AddExpressModalProps} />}
      {visible == 3 && <AddNetwork {...AddNetworkProps} />}
      {visible == 4 && <SetNetworkName {...SetNetworkNameProps} />}
      {visible == 5 && <AddFaceOrder {...AddFaceOrderProps} />}
      {visible == 6 && <SetSelectArea {...SetSelectAreaProps} />}
      {visible == 7 && <SetWarehouse {...SetWarehouseProps} />}
      {visible == 8 && <SetFreight {...SetFreightProps} />}
      {visible == 'cross' && <AddSortCross {...AddSortCrossProps} />}
    </>
  );
};
